from flask import request, current_app
from flask_restful import Resource
from flask_jwt_extended import jwt_required
from . import user_bp
from ..services.user_service import UserService
from ..utils.response import success_response, error_response
from ..middlewares.permission import check_permission

@user_bp.route('', methods=['GET'])
@jwt_required()
@check_permission()
def get_users():
    """获取用户列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('size', 10, type=int)
        keyword = request.args.get('keyword', None, type=str)
        
        # 调用service层获取数据
        result = UserService.get_user_list(page=page, per_page=per_page, keyword=keyword)
        return success_response(data=result)
    except Exception as e:
        current_app.logger.error(f"获取用户列表失败: {str(e)}")
        return error_response(message="获取用户列表失败")

@user_bp.route('', methods=['POST'])
@jwt_required()
@check_permission()
def create_user():
    """创建用户"""
    try:
        data = request.get_json()
        if not data or not data.get('username') or not data.get('password'):
            return error_response(message="用户名和密码不能为空")
        
        # 检查用户名是否已存在
        if UserService.get_user_by_username(data['username']):
            return error_response(message="用户名已存在")
        
        # 创建用户
        user = UserService.create_user(data)
        return success_response(message="创建成功", data={"id": user.id})
    except Exception as e:
        current_app.logger.error(f"创建用户失败: {str(e)}")
        return error_response(message="创建用户失败")

@user_bp.route('/<int:id>', methods=['GET'])
@jwt_required()
@check_permission()
def get_user(id):
    """获取指定用户详情"""
    try:
        user = UserService.get_user_by_id(id)
        if not user:
            return error_response(message="用户不存在", code=404)
        return success_response(data=user.to_dict())
    except Exception as e:
        current_app.logger.error(f"获取用户详情失败: {str(e)}")
        return error_response(message="获取用户详情失败")

@user_bp.route('/<int:id>', methods=['PUT'])
@jwt_required()
@check_permission()
def update_user(id):
    """更新用户信息"""
    try:
        user = UserService.get_user_by_id(id)
        if not user:
            return error_response(message="用户不存在", code=404)
        
        data = request.get_json()
        if not data:
            return error_response(message="更新数据不能为空")
        
        # 如果更新用户名，需要检查是否已存在
        if 'username' in data and data['username'] != user.username:
            if UserService.get_user_by_username(data['username']):
                return error_response(message="用户名已存在")
        
        user = UserService.update_user(user, data)
        return success_response(message="更新成功", data=user.to_dict())
    except Exception as e:
        current_app.logger.error(f"更新用户信息失败: {str(e)}")
        return error_response(message="更新用户信息失败")

@user_bp.route('/<int:id>', methods=['DELETE'])
@jwt_required()
@check_permission()
def delete_user(id):
    """删除用户"""
    try:
        user = UserService.get_user_by_id(id)
        if not user:
            return error_response(message="用户不存在", code=404)
        
        UserService.delete_user(user)
        return success_response(message="删除成功")
    except Exception as e:
        current_app.logger.error(f"删除用户失败: {str(e)}")
        return error_response(message="删除用户失败")

@user_bp.route('/<int:id>/status', methods=['PATCH'])
@jwt_required()
@check_permission()
def update_user_status(id):
    """修改用户状态"""
    try:
        user = UserService.get_user_by_id(id)
        if not user:
            return error_response(message="用户不存在", code=404)
        
        data = request.get_json()
        if 'status' not in data:
            return error_response(message="状态参数不能为空")
        
        user = UserService.update_user_status(user, data['status'])
        return success_response(message="状态更新成功", data={"status": user.status})
    except Exception as e:
        current_app.logger.error(f"更新用户状态失败: {str(e)}")
        return error_response(message="更新用户状态失败")

@user_bp.route('/<int:id>/reset-password', methods=['POST'])
@jwt_required()
@check_permission()
def reset_password(id):
    """重置用户密码"""
    try:
        user = UserService.get_user_by_id(id)
        if not user:
            return error_response(message="用户不存在", code=404)
        
        data = request.get_json()
        if not data or not data.get('new_password'):
            return error_response(message="新密码不能为空")
        
        success = UserService.reset_password(user, data['new_password'])
        if success:
            return success_response(message="密码重置成功")
        return error_response(message="密码重置失败")
    except Exception as e:
        current_app.logger.error(f"重置用户密码失败: {str(e)}")
        return error_response(message="重置用户密码失败")

@user_bp.route('/password', methods=['PUT'])
@jwt_required()
@check_permission()
def change_password():
    """修改当前用户密码"""
    try:
        # 这里需要从JWT token中获取当前用户，暂时mock一个用户
        user = UserService.get_user_by_id(1)  # TODO: 从token中获取当前用户
        
        data = request.get_json()
        if not data or not data.get('old_password') or not data.get('new_password'):
            return error_response(message="旧密码和新密码不能为空")
        
        success = UserService.change_password(user, data['old_password'], data['new_password'])
        if success:
            return success_response(message="密码修改成功")
        return error_response(message="旧密码错误")
    except Exception as e:
        current_app.logger.error(f"修改密码失败: {str(e)}")
        return error_response(message="修改密码失败") 